package cn.lili.init;

import cn.lili.modules.lucene.OnDemandIndexInitializer;
import cn.lili.modules.lucene.SearcherManagerProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author paulG
 * @since 2022/6/9
 **/
@Component
@Slf4j
public class EsGoodsIndexInitRunner implements ApplicationRunner {

    private final OnDemandIndexInitializer indexInitializer;
    private final SearcherManagerProvider searcherManagerProvider;

    @Autowired
    public EsGoodsIndexInitRunner(OnDemandIndexInitializer indexInitializer, SearcherManagerProvider searcherManagerProvider) {
        this.indexInitializer = indexInitializer;
        this.searcherManagerProvider = searcherManagerProvider;
    }

    @Override
    public void run(ApplicationArguments args) {
        log.info("应用启动完成，开始后台索引初始化...");

        // 在后台线程启动索引初始化
        new Thread(() -> {
            try {
                log.info("启动索引初始化进程...");
                indexInitializer.ensureInitialized();
                log.info("索引初始化完成");
                searcherManagerProvider.afterPropertiesSet();
            } catch (Exception e) {
                log.error("索引初始化失败", e);
            }
        }, "Index-Init-Thread").start();
    }

}
